import time
import os
import re
import pandas
import openpyxl
from voice_handle import analyze_tone_and_speed2,analyze_tone_and_speed
from openpyxl.styles import Alignment
from collections import deque
from copy import deepcopy
import sys


def add_biaodianfuhao(string):
    """
    检查句末，添加标点符号
    """
    if string[-1] not in [".", "。", "?", "？", "!","！","”",":","："]:
        string = string + "。"
    return string


# 将一个txt文件的内容，按照第几章进行分割
def SplitFile(file_path1, dst):
    with open(file_path1, 'r',encoding="gbk",errors="ignore") as f1:
        # 获取file的名称
        file_dir1 = file_path1.replace("\\", '/').split("/")[-1].split(".")[0]
        path1 = os.path.join(dst, file_dir1)
        if not os.path.exists(path1):
            os.makedirs(path1)
        i = 1
        part_name = os.path.join(path1,"s001")
        # 获取文件每一行
        for line in f1.readlines():
            try:
                if ("正文 【" in line) :
                    name = line.replace("正文 【","").replace("】","").strip()
                    # name = line.strip()
                    i += 1
                    part_name = os.path.join(path1,name)
                    with open(part_name,"a+") as f2:
                        f2.write(line)
                else:
                    fp = open(part_name, 'a+')
                    fp.write(line)
                    fp.close()
            except Exception as e:
                print(e)


# 将一个txt文件的内容，按照数字顺序进行分割
def SplitFile_by_Num(file_path2, dst):
    with open(file_path2, 'rb') as f2:
        lines2 = f2.readlines()
        file_dir2 = file_path2.replace("\\", '/').split("/")[-1].split(".")[0]
        path2 = os.path.join(dst, file_dir2)
        if not os.path.exists(path2):
            os.makedirs(path2)
        i = 1
        for line in lines2:
            try:
                if ("%s\r\n" % i) in line or ("%s、" % i in line) or ("%s " % i in line) or str(i) in line:
                    name = line.strip().decode('utf8')
                    i += 1
                else:
                    fp = open(file_name2, 'ab+')
                    fp.write(line)
                    fp.close()
                file_name2 = os.path.join(path2, "%s_%s.txt" % (i-1, name))
            except Exception as e:
                 print(e)

# 将一个txt文件的内容，按照章节进行分割,存放在Excel中
def SplitFile_to_excel( file_path1, dst):
        """
        可单独使用
        将一个txt文件的内容的函数，按照第几章进行分割
        :param file_path1: txt文件路径
        :param dst: 输出路径
        :return:
        """
        voice_param_map = {
        "very_low":1.0,
        "low":2.0,
        "moderate":3.0,
        "high":4.0,
        "very_high":5.0
    }

        vioce_base = ["旁白2" ,"旁白"]
        with open(file_path1, 'r', encoding="utf-8", errors="ignore") as f1:
            # 获取file的名称
            file_dir1 = file_path1.replace("\\", '/').split("/")[-1].split(".")[0]
            path1 = os.path.join(dst, file_dir1) # 保存路径
            os.makedirs(path1,exist_ok=True)  # 创建文件夹

            wb = openpyxl.Workbook()  # 创建一个工作簿
            current_name = os.path.join(path1, "s001.xlsx")   # 初始化excel工作表
            sheet = wb.active  
            # 获取文件每一行
            txt_line_list = list(f1.readlines())

            # 创建最大长度为2的deque（作为栈使用），用于推理时提供更长的原文参考
            stack = deque(maxlen=2)    #文本太长了AI也处理不了。。 暂时不用deque

            zhangjie_txt = ""
            def zhangjie_handle(txt,pretxt):
                sheet_add_list = []
                tt1 = txt.split("\n")
                tt2 = []
                for t in tt1:
                    t_temp = re.split("(“.+?”)", t) 
                    for t_temp_sub in t_temp:
                        if t_temp_sub != "":
                            if len(t_temp_sub) > 100 and "”" not in t_temp_sub:
                                tt2.extend(t_temp_sub.split("。"))
                            else:
                                tt2.append(t_temp_sub)
                
                sheet_add_list = deepcopy(tt2)
                infer_t= {}
                for index,t in enumerate(tt2):    # 预先分类放入集合
                    if "“" not in t:
                        if t != "":
                            t = t.strip()
                            result = analyze_tone_and_speed(t)
                            seed = vioce_base[1]
                            sheet_add_list[index] = [seed,t,result["音调"],result["语速"]]
                    else:
                        if t != "":
                            t = t.strip()
                            t = add_biaodianfuhao(t)
                            sheet_add_list[index] = analyze_tone_and_speed2(t,pretxt,actor=True)

                return sheet_add_list
            
            for index,line in enumerate(txt_line_list):
                # 按照章节分割 匹配方式可以改变
                # if (re.search("^第.+章：",line)) :
                if (re.search("^第.+章：",line)) :
                    name = line.replace("【","").replace("】","").strip() 
                    print(line)
                    # 章节正文处理后，写入
                    # stack.append(zhangjie_txt)
                    # pretxt ="\n".join(stack)   #暂时不用deque
                    pretxt = zhangjie_txt+txt_line_list[index+1]+txt_line_list[index+2]+txt_line_list[index+3]
                    if len(zhangjie_txt) != 0:
                        sheet_add_list = zhangjie_handle(zhangjie_txt,pretxt)
                        for s in sheet_add_list:
                            if isinstance(s,list):
                                sheet.append(s)
                            elif isinstance(s,dict):
                                sheet.append(list(s.values()))
                            else:
                                print("错误！！！",s)

                    #保存章节
                    wb.save(current_name)  
                    wb.close()   # 获取章节名
                    time.sleep(2)  # 等待2秒

                    # 每个章节重新定义一个工作表
                    current_name = os.path.join(path1, name.replace(" ", "_") + ".xlsx") 
                    print(current_name)  
                    wb = openpyxl.Workbook() 
                    sheet = wb.active   # 获取当前活跃的工作表
                    sheet.column_dimensions["B"].width = 80  #设置列宽
                    sheet.append(["seed", "text",
                                    'pitch', "speed", "volume"])  # 添加标题行
                    sheet.append([vioce_base[1],line,3,3]) 
                    zhangjie_txt = ""
                else:
                    line = line.strip()
                    line = line.replace("\u3000", "")
                    if line != "":
                        if line[-1] != "\n":
                            line += "\n"
                        zhangjie_txt += line
            else:
                if len(zhangjie_txt) != 0:
                    pretxt = zhangjie_txt
                    sheet_add_list = zhangjie_handle(zhangjie_txt,pretxt)
                    for s in sheet_add_list:
                        if isinstance(s,list):
                            sheet.append(s)
                        elif isinstance(s,dict):
                            sheet.append(list(s.values()))
                        else:
                            print("错误！！！",s)

                    #保存章节
                    wb.save(current_name)   # 保存最后一个工作表
                    wb.close()   # 关闭工作簿
                    zhangjie_txt = ""

# 获取某个目录下面的所有txt
def get_all_txt(path):
    filepaths = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if '.txt' in name:
                filepaths.append(os.path.join(root, name))
    return filepaths


def demo(arg1: str,index: int) -> str:
    f = open(arg1, "r", encoding="utf-8")
    flag = index
    arg2 = ""
    for line in f.readlines():
        if (re.search("^第.+章",line)) and flag != 0:
            flag = flag - 1
            arg2 = line.strip()
        elif (re.search("^第.+章",line)) and flag == 0:
            return arg2
        else:
            arg2 += line.strip()

def main(arg1: str):
    generater = demo(arg1)
    return next(generater)

def demo(arg1: str) -> str:
    with open(arg1, "r", encoding="utf-8") as f:
        text = ""
        flag = 0
        for line in f.readlines():
            if (re.search("^%s"%str,line)) :
                text += line.strip()
                flag = 1
            elif (re.search("^第.+章",line)):
                return text
            elif flag == 1:
                text += line.strip()
            else:
                return text

if __name__ == "__main__":
    dst = r"E:\txt\明朝败家子"   # 生成文件目录
    file_path = r"E:\txt\明朝败家子\明朝败家子.txt"
    SplitFile_to_excel(file_path, dst)